import axios from "axios";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/token";

import useUserStore from "@/store/modules/user";
import { delEmptyQueryNodes } from "@/utils/ruoyi";

// 允许跨域
// axios.defaults.headers.post["Access-Control-Allow-Origin-Type"] = "*";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 3000,
  // 表示跨域请求时是否需要使用凭证 解决后端跨域获取不到cookie问题
  withCredentials: false,
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const token = getToken()
    if (token) {
      config.headers["token"] = token;
    }
    const method = config?.method || "get";
    const header = config?.headers["Content-Type"] ?? "";

    // if (
    //   (method.toLowerCase() === "post" || method.toLowerCase() === "put") &&
    //   header != "multipart/form-data"
    // ) {
    //   config.data = delEmptyQueryNodes(config.data);
    // }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const userStore = useUserStore()
    const token = res.headers["authorization"] || res.token;
    if (token) {
      userStore.refreshToken(token);
    }
    const resData = res.data
    const { code, err_msg } = resData;
    if(code == undefined && err_msg == undefined){
      return Promise.resolve(resData)
    }
    if(code === 200 ){
      return Promise.resolve(resData)
    }
    else if (code !== 200) {
      return Promise.reject(err_msg);
    }
    if (code === 401) {
      // ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
      //   confirmButtonText: "重新登陆",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(() => {
      //   userStore
      //     .logOut()
      //     .finally(() => {
      //       if (window.location.pathname.indexOf("/login") !== 0) {
      //         window.location.href = `${window.location.protocol}//${window.location.host}/login`;
      //       }
      //     });
      // });
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (
      code == 0 ||
      code == 1 ||
      code == 110 ||
      code == 101 ||
      code == 403 ||
      code == 500 ||
      code == 400
    ) {
      ElMessage({
        message: err_msg,
        type: "error",
      });
      return Promise.reject(err_msg);
    } else {
      return Promise.resolve(resData);
    }
  },
  (error) => {
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("code 429")) {
      message = "请求过于频繁，请稍后再试";
    } else if (message.includes("Request failed with status code")) {
      message =
        "系统接口" + message.substr(message.length - 3) + "异常，请联系管理员";
    }
    ElMessage({
      message: message,
      type: "error",
      duration: 1500,
      showClose: true,
      grouping: false,
    });
    return Promise.reject(error);
  }
);


export default service ;
